
<template>
  <div>
    <div v-if="imageUrl">
      <span class="demonstration">截图画面</span>
      <img class="img" :src="imageUrl" />
    </div>
    <el-button @click="sendScreenShotMessage" type="primary">截屏</el-button>
    <el-button v-if="imageBase64" @click="downloadImage" type="primary">下载图片</el-button>
  </div>
</template>

<script lang="ts">
import { sendToBackground } from "@plasmohq/messaging";
import { Storage } from "@plasmohq/storage";
import * as FileSaver from 'file-saver';

export default {
  name: "ScreenShot",
  data() {
    return {
      imageUrl: "",
      screenshotData: "",
      imageBase64: ""
    };
  },
  created() {
    this.retrieveBase64Data();
  },
  methods: {
    async sendScreenShotMessage() {
      console.log("send to screenShot");
      const resp = await sendToBackground({
        name: "ScreenShot",
        body: {
          message: "beginShot"
        }
      });
      this.imageUrl = resp?.message;
      console.log(resp?.message);
      // 将图片地址转换为 base64 数据
      const res = await fetch(this.imageUrl);
      const blob = await res.blob();
      const reader = new FileReader();
      reader.readAsDataURL(blob); 
      reader.onloadend = () => {
        this.imageBase64 = reader.result;
      }
    },
    async retrieveBase64Data() {
      try {
        const storage = new Storage();
        const base64Data = await storage.get("screenshot");
        this.screenshotData = base64Data;
      } catch (error) {
        console.error("Error retrieving screenshot base64 data", error);
      }
    },
    downloadImage() {
      // 使用 FileSaver.js 库保存下载的文件
      const imageBlob = this.dataURItoBlob(this.imageBase64);
      FileSaver.saveAs(imageBlob, 'screenshot.png');
    },
    dataURItoBlob(dataURI: string) {
      const byteString = atob(dataURI.split(',')[1]);
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: 'image/png' });
    }
  }
};
</script>

<style scoped>
.img {
  max-width: 100%;
  height: auto;
}
.demonstration {
  font-family: '宋体', sans-serif;
  font-size: 24px;
  color: lightblue;
}
</style>
